package com.srwl.mytx.camera2;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.MeteringRectangle;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.srwl.mytx.activity.VideoRecordActivityV2;
import com.srwl.mytx.domain.Message;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class CameraController implements CameraTouch.CallBack {
    private static final String TAG = "CameraController";
    private static Activity mActivity;
    private String mFolderPath; //保存视频,图片的文件夹路径
    private ImageReader mImageReader;
    private HandlerThread mBackgroundThread;
    private Handler mBackgroundHandler;
    private AutoFitTextureView mTextureView;
    private Semaphore mCameraOpenCloseLock = new Semaphore(1);//一个信号量以防止应用程序在关闭相机之前退出。
    private String mCameraId;//当前相机的ID。
    private CameraDevice mCameraDevice;
    private Size mPreviewSize;
    private Size recordSize;
    private CaptureRequest mPreviewRequest;
    private File mFile;//拍照储存文件
    private Integer mSensorOrientation;
    private CameraCaptureSession mPreviewSession;
    private CaptureRequest.Builder mPreviewBuilder;
    private CameraManager manager;
    //private CameraTouch cameraTouch;

    private static final int MAX_PREVIEW_WIDTH = 1920;//Camera2 API保证的最大预览宽度

    private static final int MAX_PREVIEW_HEIGHT = 1080;//Camera2 API保证的最大预览高度

    private boolean mFlashSupported = false;
    private int mState = STATE_PREVIEW;
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();

    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
    private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
    private static final int STATE_PREVIEW = 0;//相机状态：显示相机预览。
    private static final int STATE_WAITING_LOCK = 1;//相机状态：等待焦点被锁定。
    private static final int STATE_WAITING_PRECAPTURE = 2;//等待曝光被Precapture状态。
    private static final int STATE_WAITING_NON_PRECAPTURE = 3;//相机状态：等待曝光的状态是不是Precapture。
    private static final int STATE_PICTURE_TAKEN = 4;//相机状态：拍照。
    private MediaRecorder mMediaRecorder;
    private String mNextVideoAbsolutePath;
    private CameraType mNowCameraType;
    private Rect mZoomRect;
    private double mMaxZoom; //最大缩放尺寸
    private Size mZoomSize;
    private Rect mPreviewRect;
    private Rect mFocusRect = new Rect();
    private CoordinateTransformer mCoordinateTransformer; //坐标转换器
    private Surface previewSurface;
    private float finger_spacing;
    private int zoom_level = 1;
    private float maxzoom;
    private CameraCharacteristics characteristics;

    public CameraController(Activity activity) {
        mActivity = activity;
        //cameraTouch = new CameraTouch();
       // cameraTouch.setCallBack(this);
    }

    public void initCamera(AutoFitTextureView textureView) {
        this.mTextureView = textureView;

        this.mNowCameraType = CameraType.BACK;//默认打开后边的摄像头
        if (mTextureView.isAvailable()) {
            openCamera(mNowCameraType);
        } else {
            mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
        }

    }

    /**
     * 设置需要保存文件的文件夹路径
     *
     * @param path
     */
    public void setFolderPath(String path) {
        this.mFolderPath = path;
        File mFolder = new File(path);
        if (!mFolder.exists()) {
            mFolder.mkdirs();
            Log.d(TAG, "文件夹不存在去创建");
        } else {
            Log.d(TAG, "文件夹已创建");
        }
    }

    public void setFilePath(String videoPath) {
        mNextVideoAbsolutePath = videoPath;
    }

    public String getFolderPath() {
        return mFolderPath;
    }


    /**
     * 开始录像
     */
    public void startRecordingVideo() {

        if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
            return;
        }
        try {
            // closePreviewSession();
            setUpMediaRecorder();
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
            List<Surface> surfaces = new ArrayList<>();

            //为相机预览设置曲面
            previewSurface = new Surface(texture);
            surfaces.add(previewSurface);
            mPreviewBuilder.addTarget(previewSurface);

            //设置MediaRecorder的表面
            Surface recorderSurface = mMediaRecorder.getSurface();
            surfaces.add(recorderSurface);
            mPreviewBuilder.addTarget(recorderSurface);

            // 启动捕获会话
            // 一旦会话开始，我们就可以更新UI并开始录制
            mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {

                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    mPreviewSession = cameraCaptureSession;
                    updatePreview();
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            //开启录像
                            mMediaRecorder.start();
                        }
                    });
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {


                }
            }, mBackgroundHandler);
        } catch (CameraAccessException | IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 停止录像
     */
    public void stopRecordingVideo() {
        try {
            mPreviewSession.stopRepeating();
            mPreviewSession.abortCaptures();
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        mMediaRecorder.stop();
        mMediaRecorder.reset();
        // mMediaRecorder.release();
        mNextVideoAbsolutePath = null;
        startPreview();
    }

    private void closePreviewSession() {
        if (mPreviewSession != null) {
            mPreviewSession.close();
            mPreviewSession = null;
        }
    }

    private void setUpMediaRecorder() throws IOException {

        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); //设置用于录制的音源
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);//开始捕捉和编码数据到setOutputFile（指定的文件）
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); //设置在录制过程中产生的输出文件的格式
        if (mNextVideoAbsolutePath == null || mNextVideoAbsolutePath.isEmpty()) {
            mNextVideoAbsolutePath = getVideoFilePath();
        }
        mMediaRecorder.setOutputFile(mNextVideoAbsolutePath);//设置输出文件的路径
        // mMediaRecorder.setVideoEncodingBitRate(10000000);//设置录制的视频编码比特率
        mMediaRecorder.setVideoEncodingBitRate(3500000);//设置录制的视频编码比特率
        mMediaRecorder.setVideoFrameRate(30);//设置要捕获的视频帧速率
        mMediaRecorder.setVideoSize(recordSize.getWidth(), recordSize.getHeight());//设置要捕获的视频的宽度和高度
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//设置视频编码器，用于录制

//        mMediaRecorder.setAudioEncodingBitRate(8000);
//        mMediaRecorder.setAudioChannels(1);
//        mMediaRecorder.setAudioSamplingRate(8000);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);//设置audio的编码格式
        int rotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
        Log.d(TAG, "setUpMediaRecorder: " + rotation);


        if (mNowCameraType == CameraType.BACK)   //后置摄像头图像要旋转90度
            mMediaRecorder.setOrientationHint(90);
        else
            mMediaRecorder.setOrientationHint(270);   //前置摄像头图像要旋转270度

//        switch (mSensorOrientation) {
//            case SENSOR_ORIENTATION_DEFAULT_DEGREES:
//                mMediaRecorder.setOrientationHint(ORIENTATIONS.get(rotation));
//                break;
//            case SENSOR_ORIENTATION_INVERSE_DEGREES:
//                mMediaRecorder.setOrientationHint(ORIENTATIONS.get(rotation));
//                break;
//        }
        mMediaRecorder.prepare();
    }

    private String getVideoFilePath() {

        return getFolderPath() + "/" + System.currentTimeMillis() + ".mp4";
    }

    private void updatePreview() {
        if (null == mCameraDevice) {
            return;
        }
        try {
            //  mPreviewBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
            HandlerThread thread = new HandlerThread("CameraPreview");
            thread.start();
            mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取当前时间,用来给文件夹命名
     */
    private String getNowDate() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(new Date());
    }

    private TextureView.SurfaceTextureListener mSurfaceTextureListener
            = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            openCamera(CameraType.BACK);
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {

        }
    };

    public void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("CameraBackground");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());

    }
    /**
     * Stops the background thread and its {@link Handler}.
     */
    public void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 开启相机
     */
    private void openCamera(CameraType cameraType) {
        //设置相机输出
        setUpCameraOutputs(cameraType);
        //配置变换
        // configureTransform(width, height);
        manager = (CameraManager) mActivity.getSystemService(Context.CAMERA_SERVICE);
        try {
            if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("Time out waiting to lock camera opening.");
            }

            if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

                return;
            }
            //打开相机预览
            manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);


        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
        }
    }


    /**
     * CameraDevice状态更改时被调用。
     */
    private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            // 打开相机时调用此方法。 在这里开始相机预览。
            mCameraOpenCloseLock.release();
            mCameraDevice = cameraDevice;
            //创建CameraPreviewSession
            startPreview();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
            Log.i(TAG, "onDisconnected: mCameraDevice 销毁了");
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int error) {
            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
            Log.i(TAG, "onDisconnected: mCameraDevice 销毁了");
            mActivity.finish();
        }

    };

    /**
     * 为相机预览创建新的CameraCaptureSession
     */
    private void startPreview() {
        try {
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;


            // 将默认缓冲区的大小配置为我们想要的相机预览的大小。 设置分辨率
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());

            // 预览的输出Surface。
            previewSurface = new Surface(texture);

            //设置了一个具有输出Surface的CaptureRequest.Builder。
            mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            mPreviewBuilder.addTarget(previewSurface);

            //创建一个CameraCaptureSession来进行相机预览。
            mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, mImageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {

                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                            // 相机已经关闭
                            if (null == mCameraDevice) {
                                return;
                            }

                            // 会话准备好后，我们开始显示预览
                            mPreviewSession = cameraCaptureSession;
                            // 自动对焦应
                            mPreviewBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

                            // 最终开启相机预览并添加事件
                            mPreviewRequest = mPreviewBuilder.build();
                            try {
                                mPreviewSession.setRepeatingRequest(mPreviewRequest,
                                        mCaptureCallback, mBackgroundHandler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(
                                @NonNull CameraCaptureSession cameraCaptureSession) {

                        }
                    }, null
            );
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理与JPEG捕获有关的事件
     */
    private CameraCaptureSession.CaptureCallback mCaptureCallback
            = new CameraCaptureSession.CaptureCallback() {

        //处理
        private void process(CaptureResult result) {
            switch (mState) {
                case STATE_PREVIEW: {
                    //预览状态
                    break;
                }

                case STATE_WAITING_LOCK: {
                    //等待对焦
                    Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
                    if (afState == null) {
                        captureStillPicture();
                    } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState ||
                            CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) {
                        // 某些设备上的控制状态可以为空
                        Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                        if (aeState == null || aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
                            mState = STATE_PICTURE_TAKEN;
                            captureStillPicture();
                        } else {
                            runPrecaptureSequence();
                        }
                    }
                    break;
                }
                case STATE_WAITING_PRECAPTURE: {
                    //某些设备上的控制状态可以为空
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null ||
                            aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
                            aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
                        mState = STATE_WAITING_NON_PRECAPTURE;
                    }
                    break;
                }
                case STATE_WAITING_NON_PRECAPTURE: {
                    // CONTROL_AE_STATE can be null on some devices
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
                        mState = STATE_PICTURE_TAKEN;
                        captureStillPicture();
                    }
                    break;
                }
            }
        }

        @Override
        public void onCaptureProgressed(@NonNull CameraCaptureSession session,
                                        @NonNull CaptureRequest request,
                                        @NonNull CaptureResult partialResult) {
            process(partialResult);
        }

        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                       @NonNull CaptureRequest request,
                                       @NonNull TotalCaptureResult result) {
            process(result);
        }

    };

    /**
     * 拍摄静态图片。
     */
    private void captureStillPicture() {


        try {
            if (null == mCameraDevice) {
                return;
            }
            // 这是用来拍摄照片的CaptureRequest.Builder。
            final CaptureRequest.Builder captureBuilder =
                    mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(mImageReader.getSurface());

            // 使用相同的AE和AF模式作为预览。
            captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            setAutoFlash(captureBuilder);

            // 方向
            int rotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));

            CameraCaptureSession.CaptureCallback CaptureCallback
                    = new CameraCaptureSession.CaptureCallback() {

                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                               @NonNull CaptureRequest request,
                                               @NonNull TotalCaptureResult result) {
                    showToast("图片地址: " + mFile);
                    Log.d(TAG, mFile.toString());
                    unlockFocus();
                }
            };
            //停止连续取景
            mPreviewSession.stopRepeating();
            //捕获图片
            mPreviewSession.capture(captureBuilder.build(), CaptureCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private void showToast(final String text) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mActivity, text, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private int getOrientation(int rotation) {

        return (ORIENTATIONS.get(rotation) + mSensorOrientation + 270) % 360;
    }

    private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
        if (mFlashSupported) {
            requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                    CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
        }
    }

    /**
     * 解锁焦点
     */
    private void unlockFocus() {
        try {
            // 重置自动对焦
            mPreviewBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                    CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
            setAutoFlash(mPreviewBuilder);
            mPreviewSession.capture(mPreviewBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
            // 将相机恢复正常的预览状态。
            mState = STATE_PREVIEW;
            // 打开连续取景模式
            mPreviewSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 运行捕获静止图像的预捕获序列。 当我们从{@link #（）}的{@link #mCaptureCallback}中得到响应时，应该调用此方法。
     */
    private void runPrecaptureSequence() {
        try {
            // 这是如何告诉相机触发的。
            mPreviewBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
                    CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
            // 告诉 mCaptureCallback 等待preapture序列被设置.
            mState = STATE_WAITING_PRECAPTURE;
            mPreviewSession.capture(mPreviewBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private ImageReader.OnImageAvailableListener mOnImageAvailableListener
            = new ImageReader.OnImageAvailableListener() {
        @Override
        public void onImageAvailable(ImageReader reader) {
            //等图片可以得到的时候获取图片并保存
            mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(), mFile));
        }
    };


    /**
     * 设置与相机相关的成员变量。
     */
    private void setUpCameraOutputs(CameraType cameraType) {
        int cameraTypeId;
        switch (cameraType) {
            default:
            case BACK:
                cameraTypeId = CameraCharacteristics.LENS_FACING_BACK;
                break;
            case FRONT:
                cameraTypeId = CameraCharacteristics.LENS_FACING_FRONT;
                break;
            case USB:
                cameraTypeId = CameraCharacteristics.LENS_FACING_EXTERNAL;
                break;
        }
        CameraManager manager = (CameraManager) mActivity.getSystemService(Context.CAMERA_SERVICE);
        //获取摄像头列表
        try {
            String[] cameraIdList = manager.getCameraIdList();
            for (String cameraId : cameraIdList) {
                characteristics = manager.getCameraCharacteristics(cameraId);

                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing != null && facing != cameraTypeId) {
                    continue;
                }
                StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                if (map == null) {
                    continue;
                }
                Float maxZoom = characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
                if (maxZoom != null) {
                    mMaxZoom = maxZoom.floatValue();
                }
                //对于静态图像拍照, 使用最大的可用尺寸
                Size largest = Collections.max(
                        Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                        new CompareSizesByArea()
                );
                mZoomSize = largest;
                mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, 2);
                mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
                //获取手机旋转的角度以调整图片的方向

                int displayRotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
                mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
                boolean swappedDimensions = false;

                switch (displayRotation) {
                    case Surface.ROTATION_0:
                    case Surface.ROTATION_180:
                        //横屏
                        if (mSensorOrientation == 90 || mSensorOrientation == 270) {
                            swappedDimensions = true;
                        }
                        break;
                    case Surface.ROTATION_90:
                    case Surface.ROTATION_270:
                        //竖屏
                        if (mSensorOrientation == 0 || mSensorOrientation == 180) {
                            swappedDimensions = true;
                        }
                        break;
                    default:
                        Log.e(TAG, "Display rotation is invalid: " + displayRotation);
                }

                Point displaySize = new Point();
                mActivity.getWindowManager().getDefaultDisplay().getSize(displaySize);
                int maxPreviewWidth = displaySize.x;
                int maxPreviewHeight = displaySize.y;

                if (swappedDimensions) {
                    maxPreviewWidth = displaySize.y;
                    maxPreviewHeight = displaySize.x;
                }

                if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                }

                if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                }

                DisplayMetrics displayMetrics = new DisplayMetrics();
                mActivity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                int widthPixels = displayMetrics.widthPixels;
                int heightPixels = displayMetrics.heightPixels;
                Log.d(TAG, " 屏幕尺寸 widthPixels: " + widthPixels + "____heightPixels:" + heightPixels);

                //尝试使用太大的预览大小可能会超出摄像头的带宽限制
                Size[] outputSizes = map.getOutputSizes(SurfaceTexture.class);
//                mPreviewSize = chooseOptimalSize(outputSizes,  //这个获取的预览尺寸不行，和屏幕比例失调，看起变形了，
//                        rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
//                        maxPreviewHeight, largest);

                List<Size> previewSizes = Arrays.asList(outputSizes);
                mPreviewSize = getOptimalVideoSize_new(previewSizes, widthPixels, heightPixels);
                Log.i(TAG, "竖屏最优预览尺寸: " + "height:" + mPreviewSize.getHeight() + "width:" + mPreviewSize.getWidth());
                recordSize = getSupportedVideoSizes(previewSizes);
                Log.i(TAG, "setUpCameraOutputs: 录制尺寸：height:" + recordSize.getHeight() + " width :" + recordSize.getWidth());

                //检查是否这个摄像头是否支持闪光灯，拍照模式的时候使用
                Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                mFlashSupported = available == null ? false : available;
                // int orientation = mActivity.getResources().getConfiguration().orientation;

                // 竖屏
                 mTextureView.setAspectRatio(widthPixels, heightPixels);
                mPreviewRect = new Rect(0, 0, mTextureView.getWidth(), mTextureView.getHeight());
                mCoordinateTransformer = new CoordinateTransformer(characteristics, new RectF(mPreviewRect));
                mMediaRecorder = new MediaRecorder();

                mCameraId = cameraId;
                return;
            }
        } catch (CameraAccessException e) {


        }

    }

    @Override
    public void onScaleChange(float scale) {
        cameraZoom(scale);
    }

    public float getMaxZoom() {
        return maxzoom;
    }

    /**
     * 根据他们的区域比较两个Size
     */
    static class CompareSizesByArea implements Comparator<Size> {

        @Override
        public int compare(Size lhs, Size rhs) {
            // 我们在这里投放，以确保乘法不会溢出
            return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
                    (long) rhs.getWidth() * rhs.getHeight());
        }

    }

    private static Size chooseOptimalSize(Size[] choices, int textureViewWidth,
                                          int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) {

        // 收集支持的分辨率，这些分辨率至少与预览图面一样大
        List<Size> bigEnough = new ArrayList<>();
        // 收集小于预览表面的支持分辨率
        List<Size> notBigEnough = new ArrayList<>();
        int w = aspectRatio.getWidth();
        int h = aspectRatio.getHeight();
        for (Size option : choices) {
            if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
                    option.getHeight() == option.getWidth() * h / w) {
                if (option.getWidth() >= textureViewWidth &&
                        option.getHeight() >= textureViewHeight) {
                    bigEnough.add(option);
                } else {
                    notBigEnough.add(option);
                }
            }
        }
        //挑一个足够大的最小的。如果没有一个足够大的，就挑一个不够大的。
        if (bigEnough.size() > 0) {
            return Collections.min(bigEnough, new CompareSizesByArea());
        } else if (notBigEnough.size() > 0) {
            return Collections.max(notBigEnough, new CompareSizesByArea());
        } else {
            Log.d(TAG, "Couldn't find any suitable preview size");
            return choices[0];
        }
    }

    private void configureTransform(int viewWidth, int viewHeight) {
        if (null == mTextureView || null == mPreviewSize) {
            return;
        }
        int rotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
        Matrix matrix = new Matrix();
        RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
        RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
        float centerX = viewRect.centerX();
        float centerY = viewRect.centerY();
        if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
            bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
            matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
            float scale = Math.max(
                    (float) viewHeight / mPreviewSize.getHeight(),
                    (float) viewWidth / mPreviewSize.getWidth());
            matrix.postScale(scale, scale, centerX, centerY);
            matrix.postRotate(90 * (rotation - 2), centerX, centerY);
        } else if (Surface.ROTATION_180 == rotation) {
            matrix.postRotate(180, centerX, centerY);
        }
        mTextureView.setTransform(matrix);
    }


    /**
     * 将JPG保存到指定的文件中。
     */
    private static class ImageSaver implements Runnable {

        /**
         * JPEG图像
         */
        private final Image mImage;
        /**
         * 保存图像的文件
         */
        private final File mFile;

        public ImageSaver(Image image, File file) {
            mImage = image;
            mFile = file;
        }

        @Override
        public void run() {
            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            FileOutputStream output = null;
            try {
                output = new FileOutputStream(mFile);
                output.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                mImage.close();
                if (null != output) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }


    /**
     * 同时从 分辨率高宽比和像素点面积两个维度来判断各个预览分辨率与目标分辨率的差别
     * 差别最小的，作为预览分辨率
     * 经过但愿测试 非常科学
     *
     * @param previewSizes
     * @param surfaceViewWidth
     * @param surfaceViewHeight
     * @return
     */
    private Size getOptimalVideoSize_new(List<Size> previewSizes, int surfaceViewWidth, int surfaceViewHeight) {
        Size previewSize = null;
        double totalDifference = Double.MAX_VALUE;
        double targetRatio = (double) surfaceViewHeight / surfaceViewWidth;
        Log.i(TAG, "getOptimalVideoSize_new: targetRatio :" + targetRatio);
        long targetArea = surfaceViewWidth * surfaceViewHeight;
        Log.i(TAG, "getOptimalVideoSize_new: targetArea :" + targetArea);
        for (int i = 0; i < previewSizes.size(); i++) {
            double ratio = ((double) previewSizes.get(i).getWidth()) / previewSizes.get(i).getHeight();
            double ratioDifference = Math.abs(ratio - targetRatio);
            Size size = previewSizes.get(i);
            long area = size.getWidth() * previewSizes.get(i).getHeight();
            double areaDifference = (double) Math.abs(area - targetArea) / targetArea;
            double currentTotalDifference = ratioDifference + areaDifference;
            //计算方差,估计叫 方差 ，表示数据的离散程度，我们希望找到 在面积、高宽比都与期望值比较接近的，而不是一个完全一样，一个相去甚远，好比是寻找学生中 成绩总体不错的，而不是要 偏科生。
            double variance = (Math.pow((Math.abs(ratioDifference - currentTotalDifference / 2)), 2) + Math.pow((Math.abs(areaDifference - currentTotalDifference / 2)), 2)) / 2;
            Log.i(TAG, "getOptimalVideoSize_new: variance :" + variance);
            currentTotalDifference = currentTotalDifference + variance;
            Log.i(TAG, "getOptimalVideoSize_new: currentTotalDifference :" + currentTotalDifference + " size.width:" + size.getWidth() + "  size.height:" + size.getHeight());
            if (currentTotalDifference < totalDifference) {
                totalDifference = currentTotalDifference;
                previewSize = size;
            }
        }
        return previewSize;
    }

    /**
     * 获取录制分辨率
     *
     * @param supportedVideoSizes
     * @return
     */
    private Size getSupportedVideoSizes(List<Size> supportedVideoSizes) {

        for (Size supportedVideoSize : supportedVideoSizes) {
            Log.d(TAG, "getSupportedVideoSizes: with:" + supportedVideoSize.getWidth() + "   height:" + supportedVideoSize.getHeight());
            if (supportedVideoSize.getWidth() == 1280 && supportedVideoSize.getHeight() == 720) {
                return supportedVideoSize;
            } else if (supportedVideoSize.getWidth() == 864) {
                return supportedVideoSize;
            } else if (supportedVideoSize.getWidth() == 800) {
                return supportedVideoSize;
            } else if (supportedVideoSize.getWidth() == 720) {
                return supportedVideoSize;
            } else if (supportedVideoSize.getWidth() == 640) {
                return supportedVideoSize;
            } else if (supportedVideoSize.getWidth() == 480) {
                return supportedVideoSize;
            } else if (supportedVideoSize.getWidth() == 352) {
                return supportedVideoSize;
            }
        }

        return supportedVideoSizes.get(0);
    }


    /**
     * 摄像头类型
     */
    public enum CameraType {
        FRONT,
        BACK,
        USB
    }

    /**
     * 灯光状态
     */
    public enum FlashState {
        CLOSE,
        AUTO,
        OPEN
    }

    private FlashState mNowFlashState = FlashState.CLOSE;

    public void flashSwitchState(FlashState mFlashState) {
        mNowFlashState = mFlashState;
        //以下方式不能在预览的时候使用，否则报 摄像头以及被使用的错误
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            try {
//                if (mNowFlashState == FlashState.CLOSE) {
//                    manager.setTorchMode(mCameraId, true);
//                } else {
//                    manager.setTorchMode(mCameraId, false);
//                }
//
//            } catch (CameraAccessException e) {
//                e.printStackTrace();
//            }
//        }
        setTakePhotoFlashMode(mPreviewBuilder);
        updatePreview();

        try {
            // Change some capture settings
            // mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
            // Build new request (we can't just edit existing one, as it is immutable)
            // mPreviewRequest = mPreviewRequestBuilder.build();
            // Set new repeating request with our changed one
            mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), mCaptureCallback, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

    }

    private void setTakePhotoFlashMode(CaptureRequest.Builder builder) {
        if (!mFlashSupported)
            return;
        switch (mNowFlashState) {
            case CLOSE:
                builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
                builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
                break;
            case OPEN:
                //builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
                builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
                builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
                break;
            case AUTO:
                builder.set(CaptureRequest.CONTROL_AE_MODE,
                        CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                Log.e("mode", "自动闪光灯");
                break;
        }
    }

    public void closeCamera() {
        Log.i(TAG, "关闭摄像头");

        closePreviewSession();
        if (mCameraDevice != null) {
            mCameraDevice.close();
            mCameraDevice = null;
        }
        if (mImageReader != null) {
            mImageReader.close();
            mImageReader = null;
        }
    }

    public CameraType switchCamera() {
        closeCamera();
        if (mNowCameraType == CameraType.BACK) {
            mNowCameraType = CameraType.FRONT;
        } else {
            mNowCameraType = CameraType.BACK;
        }
        openCamera(mNowCameraType);

        return mNowCameraType;
    }


    public void cameraZoom(float scale) {
        if (scale < 1.0f)
            scale = 1.0f;
        if (scale <= mMaxZoom) {

            int cropW = (int) ((mZoomSize.getWidth() / (mMaxZoom * 2.6)) * scale);
            int cropH = (int) ((mZoomSize.getHeight() / (mMaxZoom * 2.6)) * scale);

            Rect zoom = new Rect(cropW, cropH,
                    mZoomSize.getWidth() - cropW,
                    mZoomSize.getHeight() - cropH);
            mPreviewBuilder.set(CaptureRequest.SCALER_CROP_REGION, zoom);
            mZoomRect = zoom;
            updatePreview();   //重复更新预览请求
        }
    }

    public void requestFocus(float x, float y) {
        MeteringRectangle rect = calcTapAreaForCamera2(
                mTextureView.getWidth() / 5,
                1000, x, y);

        MeteringRectangle[] AFRegions = new MeteringRectangle[]{rect};
        // AERegions = new MeteringRectangle[]{rect};

        Log.e("AFRegions", "AFRegions:" + AFRegions.toString());

        try {
            final CaptureRequest.Builder mFocusBuilder =
                    mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

            mFocusBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO);
            mFocusBuilder.set(CaptureRequest.CONTROL_AF_REGIONS, AFRegions);
            //  mFocusBuilder.set(CaptureRequest.CONTROL_AE_REGIONS, AERegions);
            if (mZoomRect != null)
                mFocusBuilder.set(CaptureRequest.SCALER_CROP_REGION, mZoomRect);
            mFocusBuilder.addTarget(previewSurface);


            // if(mRecordSurface != null) {
            // mFocusBuilder.addTarget(mRecordSurface);
            //   setRecordVideoFlashMode(mFocusBuilder);
            //  }


            mPreviewSession.setRepeatingRequest(mFocusBuilder.build(),
                    null, mBackgroundHandler);

            //      mFocusBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER, CameraMetadata.CONTROL_AE_PRECAPTURE_TRIGGER_START);
            mFocusBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START);

            mPreviewSession.capture(mFocusBuilder.build(),
                    null, mBackgroundHandler);

        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private MeteringRectangle calcTapAreaForCamera2(int areaSize, int weight, float x, float y) {
        int left = clamp((int) x - areaSize / 2,
                mPreviewRect.left, mPreviewRect.right - areaSize);
        int top = clamp((int) y - areaSize / 2,
                mPreviewRect.top, mPreviewRect.bottom - areaSize);
        RectF rectF = new RectF(left, top, left + areaSize, top + areaSize);
        toFocusRect(mCoordinateTransformer.toCameraSpace(rectF));
        return new MeteringRectangle(mFocusRect, weight);
    }

    private static int clamp(int x, int min, int max) {
        if (x > max) {
            return max;
        }
        if (x < min) {
            return min;
        }
        return x;
    }

    private void toFocusRect(RectF rectF) {
        mFocusRect.left = Math.round(rectF.left);
        mFocusRect.top = Math.round(rectF.top);
        mFocusRect.right = Math.round(rectF.right);
        mFocusRect.bottom = Math.round(rectF.bottom);
    }

    //Determine the space between the first two fingers
    @SuppressWarnings("deprecation")
    private float getFingerSpacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }





}
